package tools

import (
	"bytes"
	"errors"
)

type StdWriter struct {
	Data []byte
}

func bytesCombine(pBytes ...[]byte) []byte {
	length := len(pBytes)
	s := make([][]byte, length)
	for index := 0; index < length; index++ {
		s[index] = pBytes[index]
	}
	sep := []byte("")
	return bytes.Join(s, sep)
}
func (StdWriter *StdWriter) Write(bytes []byte) (int, error) {
	if StdWriter.Data == nil {
		StdWriter.Data = bytes
	} else {
		StdWriter.Data = bytesCombine(StdWriter.Data, bytes)
	}

	return len(bytes), nil
}
func (StdWriter *StdWriter) GetDataString() string {
	if StdWriter.Data != nil {
		return string(StdWriter.Data)
	} else {
		return ""
	}
}

type StdWriterWithPid struct {
	StdWriter
	TaskId      string
	OnWrite     func(bytes []byte)
	MessageChan chan string
}

func (StdWriter *StdWriterWithPid) Write(bytes []byte) (int, error) {
	if StdWriter.OnWrite != nil {
		StdWriter.OnWrite(bytes)
	}
	if StdWriter.Data == nil {
		StdWriter.Data = bytes
	} else {
		StdWriter.Data = bytesCombine(StdWriter.Data, bytes)
	}
	return len(bytes), nil
}

func (StdWriter *StdWriterWithPid) Release() string {
	data := StdWriter.GetDataString()
	StdWriter.StdWriter.Data = nil
	return data
}

type StdIn struct {
}

func (stdIn *StdIn) Read(p []byte) (n int, err error) {
	return 0, errors.New("程序不允许读取系统输入")
}
